<?php
/**
 * Class WithdrawalApply
 * Desc  提现申请
 * Create on 2021/9/2 10:51
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use app\admin\model\xyb\system\Config;
use app\api\model\xyb\Wallets;
use think\Db;

class AgentWithdrawalApply extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\api\model\xyb\AgentWithdrawalApply();
    }

    public function submit(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        $real_amount = $param['real_amount'];

        $user_id = $this->auth->id;
        $walletsModel = new Wallets();
        $walletsObj = $walletsModel->where([
            'user_id'=>$user_id,
            'type'=>2,
            'status'=>'normal',
        ])->find();

        if(!$walletsObj || ($walletsObj['can_withdrawal_amount'] < $param['amount'])) {
            $this->error('余额不足');
        }

        if($this->model->where([
            'user_id'=>$user_id,
            'status'=>0,
            'app_plat'=>$param['app_plat'],
        ])->find()) {
            $this->error('已有提现申请');
        }

        $systemConfigModel = new Config();
        $withdrawal_pay_method = $systemConfigModel->where('id',1)->value('withdrawal_pay_method');
        Db::startTrans();
        try {
            $this->model->save([
                'user_id'=>$user_id,
                'amount'=>$param['amount'],
                'server_fee'=>bcsub($param['amount'],$real_amount,2),
                'arrival_amount'=>$real_amount,
                'app_plat'=>$param['app_plat'],
                'withdrawal_pay_method'=>$withdrawal_pay_method,
            ]);
            $walletsModel->save([
                'can_withdrawal_amount'  => bcsub($walletsObj['can_withdrawal_amount'],$param['amount'],2),
            ],['id' => $walletsObj['id']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * desc:代理员提现明细
     */
    public function agent_withdrawal_list()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $where['user_id'] = array('eq',$this->auth->id);
        if(isset($param['status'])) {
            $where['status'] = $this->request->param('status');
        }
        $where['app_plat'] = $this->request->param('app_plat');
        $data = $this->model->getList($this->model,$where,'amount,createtime,status,reject_reason,arrival_amount','id desc');
        $this->success('请求成功',$data);
    }
}